import { Button, Flex, Form } from 'antd';
import { SPACE } from '@/constants/themeConstant.js';
import { useEffect, useState } from 'react';
import { v4 as uuid } from 'uuid';

/**
 * 搜索表单组件
 *
 * @param onSearch 搜索回调函数
 * @param formItems 表单项配置
 * @returns {JSX.Element}
 */
export default function SearchForm({ onSearch, formItems }) {
  // 搜索表单
  const [searchForm] = Form.useForm();
  // 搜索条件
  const [searchQuery, setSearchQuery] = useState({});
  // 发请求标志
  const [shouldRequest, setShouldRequest] = useState(false);

  useEffect(() => {
    if (shouldRequest) {
      handleSearch();
      setShouldRequest(false);
    }
  }, [searchQuery, shouldRequest]);

  function handleSearch() {
    onSearch && onSearch(searchQuery);
  }

  return (
    <>
      <Form
        form={searchForm}
        layout="inline"
        name={`${uuid()}-search`}
        onValuesChange={(_, allValues) => {
          setSearchQuery(allValues);
        }}
        onFinish={() => {
          setShouldRequest(true);
        }}
        style={{
          rowGap: SPACE
        }}
      >
        {formItems}
        <Form.Item>
          <Flex gap={SPACE}>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button
              onClick={() => {
                setSearchQuery({});
                searchForm.resetFields();
                setShouldRequest(true);
              }}
            >
              重置
            </Button>
          </Flex>
        </Form.Item>
      </Form>
    </>
  );
}
